package com.ruoyi.util.service;

import com.google.gson.Gson;
import com.ruoyi.util.client.DeepSeekRequest;
import com.ruoyi.util.client.DeepSeekResponse;
import com.ruoyi.util.client.Message;

import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;

@Service
public class DeepSeekService {

    private String apiKey = "c9da33a0-72cb-46d7-bde9-b86721989aa9";

    private String apiUrl = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";

    private final RestTemplate restTemplate = new RestTemplate();

    public String callDeepSeek(String userMessage) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Authorization", "Bearer " + apiKey);

        // 构建请求体
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-r1");
        request.setMessages(List.of(new DeepSeekRequest.Message("user", userMessage)));

        // 发送请求
        HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers);
        ResponseEntity<DeepSeekResponse> response = restTemplate.exchange(
                apiUrl, HttpMethod.POST, entity, DeepSeekResponse.class);

        // 解析响应
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            return response.getBody().getChoices().get(0).getMessage().getContent();
        } else {
            throw new RuntimeException("Failed to call DeepSeek API: " + response.getStatusCode());
        }
    }

}
